<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="75px">
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备SN号" prop="snNum">
        <el-input
          v-model="queryParams.snNum"
          placeholder="请输入设备SN号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="equipmentType">
          <el-cascader
            :options="devices"
            @change="cascaderPropshhqfun"
            :props="cascaderProps"
            placeholder="请选择设备类型"
            clearable
          ></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:manage:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="manageList" @selection-change="handleSelectionChange">
      <el-table-column type="index" width="55" :rules="rules" label="序号" align="center" />
      <el-table-column label="设备名称" width="200" align="center" prop="name" />
      <el-table-column label="设备SN号" align="center" prop="snNum" />
      <el-table-column label="井盖编号" width="200" align="center" prop="code" />
      <el-table-column label="所属区域" align="center" prop="region" />
      <el-table-column label="经纬度" width="100"  align="center" prop="lat,lng" >
          <template slot-scope="scope">
              {{ scope.row.lat }}
              <br>
              {{ scope.row.lng }}
          </template>
      </el-table-column>
      <el-table-column   label="状态" align="center" prop="status" >
        <template slot-scope="scope">
            <el-tag  effect="dark" size="medium" style="width: 60px;" :type="scope.row.status == 1 ? 'success' : (scope.row.status == 0 ? 'danger' : 'danger') ">
              <dict-tag
              :options="dict.type.link_type"
              :value="scope.row.status"></dict-tag>
            </el-tag>

        </template>
      </el-table-column>
      <el-table-column label="设备负责人" align="center" prop="userName"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleList(scope.row)"
            v-hasPermi="['system:manage:edit']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:manage:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:manage:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="95px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="井盖编号"  prop="code">
              <el-select v-model="form.code" filterable placeholder="请输入井盖编号" @click.native="getCodeList">
                <el-option
                  v-for="item in codes1"
                  :key="item.code"
                  :label="item.code"
                  :value="item.code"
                 >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="设备SN号" label-width="90px"  prop="snNum">
                <el-input v-model="form.snNum"  placeholder="请输入内容" />
              </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备名称"   prop="name">
              <el-input v-model="form.name" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="equipmentTypeData" >
              <el-cascader
                :options="devices"
                v-model="equipmentTypeData"
                :props="cascaderProps"
                @change="sblxfun"
                placeholder="请选择设备类型"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属区域"  prop="region">
              <el-cascader
                size="large"
                :options="options"
                v-model="form.region"
                @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址"  prop="address">
              <el-input v-model="form.address"  placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="坐标位置"  prop="latAndlng">
              <el-input v-model="form.latAndlng"  @focus="selectLatAndLng()" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注"  prop="note">
              <el-input v-model="form.note"  type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="安装图片"  prop="img" >
          <el-upload
            class="upload-demo"
            :action="upload.url"
            :headers="upload.headers"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-upload="handlebefore"
            :on-success="handlePictureSuccess"
            :file-list="fileList"
            :on-change="uploadChange"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          </el-form-item>
          <el-form-item label="设备负责人" prop="uid">
            <el-select v-model="form.uname" placeholder="请选择设备负责人" clearable >
              <el-option v-for="user in users" :key="user.userId" :value="user.userName" @click.native="getUserfun(user)" :label="user.userName"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
      </el-form>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" v-if="urlImg" :src="urlImg" alt="">
        </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="地图选点" :visible.sync="dialogTableVisible" center :append-to-body='true' :lock-scroll="false"  width="50%">
        <my-component @latAndLngValue="pointValue"></my-component>
        <el-button type="primary" @click="dialogTableVisible = false">确 定</el-button>
        <el-button @click="dialogTableVisible = false">取 消</el-button>
    </el-dialog>

<!--    查看详情-->
    <el-dialog :title="title" :visible.sync="opens" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="95px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="井盖编号"  prop="code">
              <el-input v-model="form.code" placeholder="请输入井盖编号" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备SN号" label-width="90px"  prop="snNum">
              <el-input v-model="form.snNum"  placeholder="请输入内容" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备名称"   prop="name">
              <el-input v-model="form.name" placeholder="请输入设备名称" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="equipmentType">
              <el-cascader
                :options="devices"
                v-model="equipmentTypeData"
                :props="cascaderProps"
                placeholder="请选择设备类型"
                disabled
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属区域"  prop="region">
              <el-cascader
                size="large"
                :options="options"
                v-model="form.region"
                @change="handleChange"
                disabled>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址"  prop="address">
              <el-input v-model="form.address"  placeholder="请输入内容" disabled/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="坐标位置"  prop="latAndlng">
              <el-input v-model="form.latAndlng"  @focus="selectLatAndLng()" placeholder="请输入内容" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注"  prop="note">
              <el-input v-model="form.note"  type="textarea" placeholder="请输入内容" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="安装图片"  prop="img" >
            <el-upload
              :action="upload.url"
              :headers="upload.headers"
              list-type="picture-card"
              :on-success="handlePictureSuccess"
              :on-preview="handlePictureCardPreview"
              :file-list="fileList"
              disabled
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" v-if="urlImg" :src="urlImg" alt="">
            </el-dialog>
          </el-form-item>
          <el-form-item label="设备负责人" prop="uid">
            <el-select v-model="form.uid" placeholder="请选择设备负责人" clearable  disabled>
              <el-option v-for="user in users" :key="user.userId" :value="user.userId" :label="user.userName" ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
      </el-form>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import {
  listManage,
  getManage,
  delManage,
  addManage,
  updateManage,
  getCover,
  upload,
  userList, listCoverNum,listDeviceName
} from "@/api/system/manage";
import { pcaTextArr } from "element-china-area-data";
import MyComponent from '../../components/MyComponent.vue'
import { getToken } from "@/utils/auth";
export default {
  components:{
    'my-component': MyComponent
  },
  name: "Manage",
  dicts: ['link_type','device_type'],
  data() {
    return {
      equipmentTypeData:[],
      //设备类型
      devices:[],
      codes1:[],
      //设备负责人
      users: [],
      userLists:[],
      fileList:[],
      dialogImageUrl: '',
      urlImg:"",
      dialogVisible: false,
      disabled: false,
      options: pcaTextArr ,
      dialogTableVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备管理表格数据
      manageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      opens:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        snNum: null,
        equipmentType: null,
        region: null,
        status: null,
        devTypeId:null,
      },
      // 表单参数
      form: {
        equipmentType: []
      },
      cascaderProps: {
        value: 'groupId', // 设备类型对象的value属性名
        label: 'groupName', // 设备类型对象的label属性名
        children: 'devTypes', // 设备类型对象的子级数据属性名
      },
      // 表单校验
      rules: {
        code:[
          {required:true,message:'井盖编号不能为空',trigger:'blur'}
        ],
        snNum:[
          {required:true,message:'设备SN号',trigger:'blur'}
        ],
        region:[
          {required:true,message:'所属区域不能为空',trigger:'blur'}
        ],
        name:[
          {required:true,message:'设备名称不能为空',trigger:'blur'}
        ],
        regionId:[
          {required:true,message:'所属区域不能为空',trigger:'change'}
        ],
        address:[
          {required:true,message:'详细地址不能为空',trigger:'blur'}
        ],
        latAndlng:[
          {required:true,message:'坐标位置不能为空',trigger:'blur'}
        ],
        img: [
          { required: true, message: "请上传图片", trigger: "change" },
        ],
        uid:[
          {required:true,message:'设备负责人不能为空',trigger:'blur'}
        ]
      },
      upload:{
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 图片上传的方法地址:
        url: process.env.VUE_APP_BASE_API + "/system/manage/upload",
      },
      codes:[]
    };
  },
  created() {
    this.getList();
    this.getCode();
  },
  mounted() {
    //设备类型
    listDeviceName(null).then(response => {
      this.devices = response.rows;
      console.log(1111,this.devices)
      this.total = response.total;
      this.loading = false;
    });
    userList(null).then(response => {
      this.users = response.rows; // 将返回的用户列表数据存储在this.users中
      this.total = response.total;
    });
  },
  methods: {
    sblxfun(){
      console.log(this.equipmentTypeData)
    },
    cascaderPropshhqfun(res){
      this.queryParams.equipmentType = res[1]
      this.queryParams.devTypeId = res[0]
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 文件上传成功后的钩子函数
    handleFileSuccess(response, file, fileList){

    },
    handleDownload(file) {
      console.log("正在上传")

      console.log(file);
    },
    getCode(){
      getCover().then(res=>{
        this.codes = res.rows

      })
    },

    //图片上传成功后的回调
    handlePictureSuccess(res, file) {
      //设置图片访问路径 （url 后台传过来的的上传地址）
      this.urlImg = file.response.img;
      console.log("11",this.urlImg)
    },

    pointValue(value){
      this.form.lat = value.lat
      this.form.lng = value.lng
      this.form.latAndlng = value.lat + ',' + value.lng
    },
    selectLatAndLng(){
        this.dialogTableVisible = true
    },
    /** 查询设备管理列表 */
    getList() {
      this.loading = true;
      listManage(this.queryParams).then(response => {
        this.manageList = response.rows;
        this.pinjie();
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.fileList=[];
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        snNum: null,
        coverId: null,
        equipmentType: null,
        regionId: null,
        region: null,
        address: null,
        lat: null,
        latAndlng:null,
        lng: null,
        latestTime: null,
        note: null,
        status: null,
        isWarn: null,
        isWarnToday: null,
        isRecoverToday: null,
        isUsed: null,
        img:null
      };
      this.resetForm("form");
    },
    handleChange (value) {
      this.form.region = value
    },
    pinjie(){
      this.manageList.forEach(element => {
        element.latAndlng = element.lat + ',' + element.lng
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.equipmentTypeData=[]
      this.reset();
      this.open = true;
      this.title = "添加设备管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.id
      getManage(id).then(response => {
        //图片回显
        this.fileList = [{ url:response.data.img}]//加的是这一行
        this.form = response.data;
        this.form.latAndlng =  response.data.lat + ',' + response.data.lng
        this.form.region = response.data.region.split("/")
        this.open = true;
        this.title = "修改设备管理";
        // console.log(965,this.form);
        this.equipmentTypeData=[]
        // console.log(Number(this.form.devTypeId),Number(this.form.equipmentType));
        this.equipmentTypeData[0] = Number(this.form.devTypeId)
        this.equipmentTypeData[1] = Number(this.form.equipmentType)
       
      });
    },
    // 查看详情
    handleList(row) {
      this.reset();
      const id = row.id || this.id
      this.fileList = undefined;
      getManage(id).then(response => {
        this.form = response.data;
        this.fileList = [{ url:response.data.img}]//加的是这一行
        this.form.latAndlng =  response.data.lat + ',' + response.data.lng
        this.form.region = response.data.region.split("/")
        this.opens = true;
        console.log(this.form)
        this.title = "查看设备管理";
        this.equipmentTypeData[0] = this.form.devTypeId
        this.equipmentTypeData[1] = Number(this.form.equipmentType)
      });
    },
    //点击上传按钮
    ingUPliog(){
      upload(this.form).then(response => {
        this.$modal.msgSuccess("新增成功");
        this.open = false;
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.region = Array.isArray(this.form.region)?this.form.region.join("/"):this.form.region;
          this.form.equipmentType = this.equipmentTypeData[1] ? this.equipmentTypeData[1] :''
          this.form.devTypeId = this.equipmentTypeData[0] ? this.equipmentTypeData[0] :''
          if (this.form.id != null) {
            console.log(11,this.form.equipmentType)
            updateManage(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            let codeExists = this.codes.some(item => item.code === this.form.code);
            if (codeExists) {
              console.log(this.form)
              addManage(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).catch((err)=>{
                this.form.region = this.form.region.join('/');
              })
            } else {
              this.$modal.msgError("井盖编号不存在，请核对井盖编号");
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备管理编号为"' + ids + '"的数据项？').then(function() {
        return delManage(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleFileChange(file, fileList){
      this.form.fileList=file
      console.log(this.form.fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlebefore(file){
      console.log(312321,file)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/manage/export', {
        ...this.queryParams
      }, `manage_${new Date().getTime()}.xlsx`)
    },
    uploadChange(file, fileList) {
      this.headFile = file;
      this.headFileList = fileList;
      if(fileList.length==1) {
        let {img, ...data} = this.rules;
        this.rules = data;
      }
      this.$refs.form.clearValidate('img');
      this.hideUpload = fileList.length >= this.limitCount;
    },
    //设备负责人下拉框数据
    getUserList(){
      console.log(12321)
      this.loading = true;

    },
    getUserfun(res){
      console.log(res)
      this.form.uid = res.userId
      this.form.flastId=res.flastId
    },
    //井盖编号
    getCodeList(){
      this.loading = true;
      listCoverNum(null).then(response => {
        this.codes1 = response.rows; // 将返回的用户列表数据存储在this.users中
        this.total = response.total;
        this.loading = false;
      });
    },
  }
};
</script>
